package com.voxel.sense.infomsg.module.task.check;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.IDialog;
import com.example.com.common.view.dialog.InputDialogCallBack;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.utils.AppFileUtil;
import com.voxel.sense.infomsg.utils.OpenDocuIntentUtils;
import com.voxel.sense.infomsg.view.MyGridView;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.voxel.sense.infomsg.widget.CommonImagePagerActivity;
import com.voxel.sense.infomsg.widget.adapter.FileGriviewAdapter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnItemClick;
import cn.jzvd.Jzvd;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.response.MyTaskListInfoEntity;

/**
 * 审核任务
 */
public class CheckTaskActivitySpara extends BViewActivity<CheckTaskContractSpara.Presenter> implements CheckTaskContractSpara.View {
    @BindView(R.id.titlebar)
    TextTitleBar titlebar;
    @BindView(R.id.tv_desc)
    TextView tv_desc; //任务类型描述
    @BindView(R.id.tv_type)
    TextView tv_type;//紧急类型
    @BindView(R.id.tv_firm_name)
    TextView tv_firm_name;//公司名称
    @BindView(R.id.tv_district)
    TextView tv_district; //tv_district区地址
    @BindView(R.id.tv_address)
    TextView tv_address; //详细地址
    @BindView(R.id.tv_start_time)
    TextView tv_start_time; //时间
    @BindView(R.id.tv_people_name)
    TextView tv_people_name; //执行人
    @BindView(R.id.tv_pic_tip_desc)
    TextView tv_pic_tip_desc;
    @BindView(R.id.tv_docu_tip_desc)
    TextView tv_docu_tip_desc;
    @BindView(R.id.gridview_image)
    MyGridView gridview_image;//图片选择
    @BindView(R.id.gridview_doc)
    MyGridView gridview_doc;//文件选择
    @BindView(R.id.gridview_video)
    MyGridView gridview_video;//视频选择
    @BindView(R.id.tv_video_text_desc)
    TextView tv_video_text_desc; //上传视频的描述文本
    @BindView(R.id.btn_no_pass)
    Button btn_no_pass; //不通过按钮
    @BindView(R.id.btn_pass)
    Button btn_pass; //通过按钮
    private String mTaskNumber;

    private FileGriviewAdapter mImageAdapter;//图片展示的适配器
    private FileGriviewAdapter mDocuAdapter;//文件展示的适配器
    private FileGriviewAdapter mVideoAdapter;//文件展示的适配器
    private MyTaskListInfoEntity.BodyBean.TaskInfoListBean mBean;
    private boolean mCheckStatus;


    public static void show(Context context, MyTaskListInfoEntity.BodyBean.TaskInfoListBean bean) {
        if (bean == null) {
            return;
        }
        Intent intent = new Intent(context, CheckTaskActivitySpara.class);
        intent.putExtra(IntentConstants.OBJECT_TYPE, bean);
        context.startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.resetAllVideos();
    }

    @Override
    protected CheckTaskContractSpara.Presenter initPresenter() {
        return new CheckTaskPresenterSpara(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_mission_describe;
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        mBean = (MyTaskListInfoEntity.BodyBean.TaskInfoListBean) getIntent().getSerializableExtra(IntentConstants.OBJECT_TYPE);

        if (mBean == null) {
            ToastUtil.showToastLong(Factory.app(), "界面跳转发生错误");
            finish();
            return false;
        }
        mTaskNumber = mBean.getTaskNumber();
        return super.initArgs(bundle);
    }


    @Override
    protected void initData() {
        super.initData();
        loadTaskInfo();
        //初始化适配器
        mImageAdapter = new FileGriviewAdapter(this, Constants.file_iage);
        mDocuAdapter = new FileGriviewAdapter(this, Constants.file_docu);
        mVideoAdapter = new FileGriviewAdapter(this, Constants.file_vedio);
        gridview_image.setAdapter(mImageAdapter);
        gridview_doc.setAdapter(mDocuAdapter);
        gridview_video.setAdapter(mVideoAdapter);
        //网络拉取回任务执行的文件
        showProgressDialog("");
        mPresenter.doLoadTaskFile(mTaskNumber);
        tv_video_text_desc.setVisibility(View.GONE);
        tv_docu_tip_desc.setVisibility(View.GONE);
        tv_pic_tip_desc.setVisibility(View.GONE);
        //显示底部按钮
        btn_no_pass.setVisibility(View.VISIBLE);
    }

    //初始化任务的基本信息
    private void loadTaskInfo() {
        titlebar.setTitleText("任务执行单");
        tv_desc.setText(mBean.getTaskType());
        String taskUrgentGrade = mBean.getTaskUrgentGrade();
        if (TextUtils.isEmpty(taskUrgentGrade)) {
            tv_type.setVisibility(View.GONE);
        } else {
            tv_type.setVisibility(View.VISIBLE);
            tv_type.setText(taskUrgentGrade);
        }
        tv_district.setText(mBean.getTaskAreaName());
        tv_address.setText(mBean.getTaskObjectAddress());
        tv_start_time.setText(mBean.getTaskStartTime() + "--" + mBean.getTaskEndTime());
        tv_people_name.setText(mBean.getTaskExcutorName());
        tv_firm_name.setText(mBean.getTaskObject());

    }

    /**
     * 列表点击事件
     */
    @OnItemClick({R.id.gridview_image, R.id.gridview_doc, R.id.gridview_video})
    public void gridItemClick(GridView view, View childrenView, int position, long id) {
        switch (view.getId()) {
            case R.id.gridview_image://图片item点击事件
                pickClickEvent(position);
                break;
            case R.id.gridview_doc://文档item点击事件
                docuClickEvent(position);
                break;
            case R.id.gridview_video://视频item点击事件
                videoClickEvent(position);
                break;
        }
    }

    @OnClick({R.id.btn_no_pass, R.id.btn_pass})
    public void btnOnclick(View view) {
        switch (view.getId()) {
            case R.id.btn_pass://通过审核
                checkTask(true, "审核通过原因");
                break;
            case R.id.btn_no_pass://不通过
                checkTask(false, "不同的原因");
                break;
        }
    }

    //提交审核
    private void checkTask(final boolean statu, String title) {
        IDialog.getInstance().showInputDialog(this, title, "请输入原因",
                "取消", "提交", false, true, new InputDialogCallBack() {
                    @Override
                    public void onClick(int what, String inputText) {
                        if (IDialog.YES == what) {
                            btn_no_pass.setEnabled(false);
                            btn_pass.setEnabled(false);
                            mCheckStatus = statu;
                            mPresenter.doSubmitCheck(mBean.getTaskNumber(), inputText, statu);
                        } else {
                            btn_no_pass.setEnabled(true);
                            btn_pass.setEnabled(true);
                        }
                    }
                });
    }

    private void videoClickEvent(int position) {
        List<String> list = mVideoAdapter.getList();
        Jzvd.startFullscreenDirectly(CheckTaskActivitySpara.this, Jzvd.class, list.get(position), "");
    }

    private void docuClickEvent(int position) {
        List<String> list = mDocuAdapter.getList();
        final String fileUrl = list.get(position);
        final File dir = AppFileUtil.getCacheDir();
        final String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        File file = new File(dir, fileName);
        if (FileUtils.isFileExists(file)) {
            //文件已存在，直接打开
            docuClickEvent(file);
        } else {
            IDialog.getInstance().showChooseDialog(this, "", "是否下载文档", new DialogCallBack() {
                @Override
                public void onClick(int what) {
                    if (IDialog.YES == what) {
                        //表示请求可以传参，怎么传都行，和okgo使用方法一样
                        mPresenter.doDownDocFile(fileUrl);
                    }
                }
            });
        }
    }

    private void pickClickEvent(int position) {
        //查看图片
        CommonImagePagerActivity.showImages(CheckTaskActivitySpara.this, (ArrayList<String>) mImageAdapter.getList(), position);
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onRefreshPhoto(List datas) {
        if (datas != null && datas.size() > 0) {
            tv_pic_tip_desc.setVisibility(View.VISIBLE);
        }
        mImageAdapter.setList(datas);
    }

    @Override
    public void onRefreshDoc(List datas) {
        if (datas != null && datas.size() > 0) {
            tv_docu_tip_desc.setVisibility(View.VISIBLE);
        }
        mDocuAdapter.setList(datas);
    }

    @Override
    public void onRefreshVideo(List datas) {
        if (datas != null && datas.size() > 0) {
            tv_video_text_desc.setVisibility(View.VISIBLE);
        }
        mVideoAdapter.setList(datas);
    }

    @Override
    public void onSubmitCheck(boolean b) {
        if (b) {
            checkTaskSuccess();
        } else {
            ToastUtil.showToastLong(Factory.app(), "审核失败");
            btn_no_pass.setEnabled(true);
            btn_pass.setEnabled(true);
        }
    }

    /**
     * 审核成功后相关操作
     */
    private void checkTaskSuccess() {
        ToastUtil.showToastLong(Factory.app(), "审核提交成功");
        titlebar.setTitleText("任务执行单-已审核");
        //审核成功，改变外层列表数据
        if ("1".equals(mCheckStatus)) {
            EventBus.getDefault().post(new EventEntity(EventBusConstants.CHECK_TASK_PASS, mBean.getTaskNumber()));
        } else {
            EventBus.getDefault().post(new EventEntity(EventBusConstants.CHECK_TASK_NO_PASS, mBean.getTaskNumber()));
        }
    }

    @Override
    public void onLookDoc(File file) {
        if (FileUtils.isFileExists(file)) {
            docuClickEvent(file);
        }
    }

    private void docuClickEvent(File file) {
        String type = "text/plain";//默认文本类型
        String fileExtension = FileUtils.getFileExtension(file);
        if (Constants.EXTENSION_DOC.equals(fileExtension) || Constants.EXTENSION_DOCX.equals(fileExtension)) {
            //doc文档
            type = "application/msword";
        } else if (Constants.EXTENSION_XLS.equals(fileExtension) || Constants.EXTENSION_XLSX.equals(fileExtension)) {
            //xls文档
            type = "application/vnd.ms-excel";
        } else if (Constants.EXTENSION_PDF.equals(fileExtension)) {
            //pdf文档
            type = "application/pdf";
        } else if (Constants.EXTENSION_PPT.equals(fileExtension) || Constants.EXTENSION_PPTX.equals(fileExtension)) {
            //ppt文档
            type = "application/vnd.ms-powerpoint";
        }
        OpenDocuIntentUtils.DocuItent(this, file, type, fileExtension);
    }
}
